/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package EventHandler;

import app.bus.ProductModel;
import app.entities.Product;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import mvc.Event;

/**
 *
 * @author Tuan Long
 */
public class CartOnline implements Event {

    private List<Product> list = new ArrayList<Product>();

    @Override
    public String EventHandler(HttpServletRequest request, HttpServletResponse response) {
        String productID = request.getParameter("ProductID");
        Product p = ProductModel.getProductByID(productID);
        HttpSession session = request.getSession();
        if (session.getAttribute("sessionOnlineCart") != null) {
            list = (List<Product>) session.getAttribute("sessionOnlineCart");
            if (checkProductID(p, list)) {
                for (Product pd : list) {
                    if (pd.getId().equals(p.getId())) {
                        pd.setAmount(pd.getAmount() + 1);
                    }
                }
            } else {
                Product product = new Product();
                product.setId(p.getId());
                product.setName(p.getName());
                product.setPrice(p.getPrice());
                product.setAmount(1);
                list.add(product);
            }

        } else {
            Product product = new Product();
            product.setId(p.getId());
            product.setName(p.getName());
            product.setPrice(p.getPrice());
            product.setAmount(1);
            list.add(product);
        }
        saveCart(list, request.getSession(true));
        //saveCart(list,request,response);
        return "CartOnline.jsp";
    }

    private boolean checkProductID(Product product, List<Product> list) {
        for (Product p : list) {
            if (p.getId().equals(product.getId())) {
                return true;
            }
        }
        return false;
    }

    private void saveCart(List<Product> list, HttpSession session) {
        session.setAttribute("sessionOnlineCart", list);
    }

//    private void saveCart(List<Product> list, HttpServletRequest request, HttpServletResponse response) {
//        for (Cookie c: request.getCookies()) {
//            if(c.getName().equals("cookieOnlineCart")){
//                
//            }
//        }
//    }
}
